package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ArticleConfigMapper;
import com.heima.article.mapper.ArticleContentMapper;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleService;
import com.heima.article.service.FreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.SearchArticleVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.util.List;


@Service
@EnableAsync
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ApArticle> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleContentMapper articleContentMapper;

    @Autowired
    private ArticleConfigMapper articleConfigMapper;

    @Autowired
    private FreemarkerService freemarkerService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 加载首页-加载更多-加载更新 三位一体
     *
     * @param dto  type=1 认为是加载更多，type=2表示加载更新
     * @param type
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {
        List<ApArticle> apArticles = articleMapper.loadArticleList(dto, type);
        //3.返回数据
        return ResponseResult.okResult(apArticles);
    }


    /**
     * 保存三剑客
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult save(ArticleDto dto) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        if(apArticle.getId() == null){
            //保存文章
            this.save(apArticle);

            //保存文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            articleConfigMapper.insert(apArticleConfig);

            //保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(dto.getContent());
            apArticleContent.setArticleId(apArticle.getId());
            articleContentMapper.insert(apArticleContent);

        }else{
            // 根据文章id修改App端文章数据
            int articleCount = this.count(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, apArticle.getId()));
            if (articleCount <= 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"app文章不存在");
            }
            // 修改文章主表信息
            this.updateById(apArticle);
            // 根据文章id查询文章内容是否存在
            int contentCount = articleContentMapper.selectCount(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            if (contentCount <= 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"app文章内容不存在");
            }
            // 修改文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(dto.getContent());
            apArticleContent.setArticleId(apArticle.getId());
            articleContentMapper.updateById(apArticleContent);
        }

        //获取模版输出流
       ByteArrayInputStream render = freemarkerService.render(dto);

       String htmlFile = fileStorageService.uploadHtmlFile("", apArticle.getId().toString()+".html", render);
        apArticle.setStaticUrl(htmlFile);
        this.updateById(apArticle);

        SearchArticleVo searchArticleVo = articleMapper.loadSearchArticle(apArticle.getId());

        //同步es
        rabbitTemplate.convertAndSend(ArticleConstants.ARTICLE_ES_SYNC_TOPIC,ArticleConstants.ARTICLE_ES_SYNC_ROUTINGKEY,searchArticleVo);


        //3.返回数据,要不要返回文章id ，因为wmnews表中需要
        return ResponseResult.okResult(apArticle.getId());
    }
}
